/**
 * 商家相关接口
 */
const express = require('express')
const router = express.Router()
const pool = require("../../db/db")
const Response = require("../../utils/ResponseData")

/**
 * 1. 查询所有商家接口（支持分页）
 * 请求url：http://localhost:3001/bus/getAll/:page/:pageSize
 * @param page: 当前页码
 * @param pageSize:一页显示的条数
 */
router.get("/getAll/:page/:pageSize", (req, res, next) => {
    // 接收前端参数
    let { page, pageSize } = req.params
    // 计算startIndex
    let startIndex = (page - 1) * pageSize
    // 将pageSize转换为数值
    pageSize = parseInt(pageSize)
    // 编写sql
    const sql = "select * from business order by b_score desc limit ?,?"
    // 执行sql
    pool.querySync(sql, [startIndex, pageSize])
        .then(result => {
            if (result.length > 0) {
                res.send(Response.success(result, "商家信息查询成功！"))
            } else {
                res.send(Response.error("商家信息查询失败！"))
            }
        })
        .catch(err => {
            if (err) {
                console.log("Bus.js=>/bus/getAll接口：", err)
                next(err)
            }
        })
})
/**
 * 2. 根据id查询商家接口
 * 请求url：http://localhost:3001/bus/getById/:id
 * @param id:编号
 */
router.get("/getById/:id", (req, res, next) => {
    // 获取前端的参数
    let { id } = req.params
    // 编写sql
    const sql = "select * from business where b_id = ?"
    // 执行sql
    pool.query(sql, [id], (err, result) => {
        if (err) {
            console.log("Bus.js=>/bus/getById接口：", err)
            next(err)
            return
        }
        if (result.length > 0) {
            res.send(Response.success(result, "商家信息查询成功！"))
        } else {
            res.send(Response.error("商家信息查询失败！"))
        }
    })
})

module.exports = router